package com.ruoyi.system.service.impl;

import cn.hutool.core.util.PhoneUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mobile.company.domain.vo.*;
import com.ruoyi.mobile.user.domain.vo.*;
import com.ruoyi.system.domain.CompanyInfo;
import com.ruoyi.system.dto.company.CompanyInfoBindDto;
import com.ruoyi.system.mapper.CompanyInfoMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IMobileUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.constants.ApplyStatusConstant;
import com.ruoyi.workflow.service.ICompanyApplyService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.Date;
import java.util.List;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
@Component
public class MobileUserServiceImpl implements IMobileUserService {
    private static final Logger log = LoggerFactory.getLogger(MobileUserServiceImpl.class);
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public SysUser selectUserByPhone(String phone) {
        return userMapper.selectUserByPhone(phone);
    }

    @Override
    public SysUser selectUserByPhoneUserType(String phone,String userType) {
        return userMapper.selectUserByPhoneUserType(phone,userType);
    }


    @Override
    public void bindingPhone(UserCodeVO userCodeVO) {
        String code= redisCache.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY +"_"+userCodeVO.getPhone()+"_"+4);
        if(StringUtils.isEmpty(userCodeVO.getCode())){
            throw new ServiceException("登陆验证码不能为空！");
        }
        if(!userCodeVO.getCode().equals(code)){
            throw new ServiceException("登陆验证码不正确！");
        }
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        sysUser.setPhonenumber(userCodeVO.getPhone());
        userMapper.updateUser(sysUser);
    }

    @Override
    public void updateName(UpdateUserNameVO userNameVO) {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        sysUser.setNickName(userNameVO.getNickName());
        userMapper.updateUser(sysUser);
    }

    @Override
    public UserVO getOne() {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        UserVO userVO=new UserVO();
        userVO.setId(sysUser.getUserId()+"");
        userVO.setNickName(sysUser.getNickName());
        userVO.setPhoneNumber((String) PhoneUtil.hideBetween(sysUser.getPhonenumber()));
        return userVO;
    }



    @Override
    public void updateUserPasswordVO(UpdateUserPasswordVO updateUserPasswordVO) {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        if(!matches(sysUser,updateUserPasswordVO.getOldPassword())){
            throw new ServiceException("旧密码不正确！");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(updateUserPasswordVO.getNewPassword()));
        userMapper.updateUser(sysUser);
    }


    public void updateUserPasswordPhone(UpdateUserPasswordPhoneVO phoneVO) {
        SysUser sysUser=userMapper.selectUserByPhone(phoneVO.getPhone());
        if(sysUser==null){
            throw new ServiceException("该手机号码还未注册！");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(phoneVO.getNewPassword()));
        userMapper.updateUser(sysUser);
    }

    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }


    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Override
    public CompanyVO getCompanyOne() {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        CompanyInfo companyInfo= companyInfoMapper.selectCompanyInfoByUserId(SecurityUtils.getUserId()+"");
        CompanyVO companyVO=new CompanyVO();
        companyVO.setUserId(sysUser.getUserId().toString());
        companyVO.setCompanyId(companyInfo.getCompanyId().toString());
        companyVO.setNickName(sysUser.getNickName());
        companyVO.setCompanyName(companyInfo.getCompanyName());
        companyVO.setUnifiedSocialCreditCode(companyInfo.getUnifiedSocialCreditCode());
        companyVO.setRegisterStatus(companyInfo.getRegisterStatus());
        return companyVO;
    }

    @Autowired
    private ICompanyApplyService companyApplyService;
    @Autowired
    private ISysUserService userService;


    @Override
    public AjaxResult<CompanyInfo> registerCompany(CompanyAddVO companyAddVO) throws Exception {
        // 新增单位之前先查询数据是否存在
        String companyName = companyAddVO.getCompanyName();
        // 根据单位名称查询不属于驳回状态的单位信息
        CompanyInfoBindDto companyInfoBindDto = companyInfoMapper.selectCompanyInfoByName(companyName);
        if (companyInfoBindDto != null) {
            // 单位存在的话就需要查询状态
            String applyStatus = companyInfoBindDto.getApplyStatus();
            if(applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW.toString())||applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW_STR)) {
                return AjaxResult.warn("该单位正处于审批中");
            }
            if(applyStatus.equals(ApplyStatusConstant.COMPLETED.toString())||applyStatus.equals(ApplyStatusConstant.COMPLETED_STR)) {
                return AjaxResult.warn("该企业已认证请勿重复提交。");
            }
        }
        CompanyInfo companyInfo = companyInfoMapper.selectCompanyInfoByCompanyName(companyName);
        SysUser sysUser=userMapper.selectUserByPhone(companyAddVO.getLegalRepresentativePhone());
        if(sysUser!=null&&sysUser.getUserType().equals("11")){
            return AjaxResult.warn("法人手机号码已经绑定其他用户。");
        }
        if(sysUser==null || companyInfo==null){
            sysUser=new SysUser();
            sysUser.setNickName(companyAddVO.getLegalRepresentative());
            sysUser.setUserName(companyAddVO.getLegalRepresentativePhone());
            sysUser.setPhonenumber(companyAddVO.getLegalRepresentativePhone());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setUserType("11");
            boolean regFlag = userService.registerUser(sysUser);
            companyInfo=new CompanyInfo();
            BeanUtils.copyProperties(companyAddVO, companyInfo);
            companyInfo.setCreatedAt(new Date());
            companyInfo.setCreatedBy(sysUser.getUserId().toString());
            companyInfo.setRegisterStatus("false");
            companyInfo.setUserId(sysUser.getUserId().toString());
            companyInfoMapper.insertCompanyInfo(companyInfo);
        }
        Long companyId = companyInfo.getCompanyId();
        // 新增完毕之后直接发起流程
        companyApplyService.startFlow(String.valueOf(companyId),String.valueOf(sysUser.getUserId()));
        return AjaxResult.success(companyInfo);
    }

    @Override
    public void updateCompanyPasswordVO(UpdateCompanyPasswordVO passwordVO) {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        if(!sysUser.getUserType().equals("11")){
            throw new ServiceException("用户不是企业用户！");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(passwordVO.getPassword()));
        userMapper.updateUser(sysUser);
    }

    @Override
    public AjaxResult<CompanyInfo> validate_company_code(String unifiedSocialCreditCode) {
        CompanyInfo companyInfo = companyInfoMapper.selectCompanyInfoByCode(unifiedSocialCreditCode);
        if(companyInfo==null){
            throw new ServiceException("未找到企业信息！");
        }
        return AjaxResult.success(companyInfo);
    }

    @Override
    public List<UserListVO> selectUserList(UserSearchVO userSearchVO) {
        return userMapper.selectH5UserList(userSearchVO);
    }

    @Override
    public List<CompanyListVO> selectCompanyUserList(CompanySearchVO companySearchVO) {
        return userMapper.selectCompanyUserList(companySearchVO);
    }

    public static void main(String[] args) {
        String s="2";
        System.out.println(s.equals(2+""));
    }

    @Override
    public void validateCompany(CompanyValidateVO validateVO) {
        CompanyInfoBindDto companyInfoBindDto = companyInfoMapper.selectCompanyInfoByName(validateVO.getCompanyName());
        if (companyInfoBindDto != null) {
            // 单位存在的话就需要查询状态
            String applyStatus = companyInfoBindDto.getApplyStatus();
            log.info("applyStatus:::::::"+applyStatus);
            if(applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW.toString())||applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW_STR)) {
                throw new ServiceException("该单位正处于审批中！");
            }
        }
    }

    @Override
    public void validateCompanyState(CompanyValidateVO validateVO) {
        CompanyInfoBindDto companyInfoBindDto = companyInfoMapper.selectCompanyInfoByName(validateVO.getCompanyName());
        if (companyInfoBindDto != null) {
            // 单位存在的话就需要查询状态
            String applyStatus = companyInfoBindDto.getApplyStatus();
            log.info("applyStatus:::::::"+applyStatus);
           if (applyStatus.equals(ApplyStatusConstant.COMPLETED.toString())||applyStatus.equals(ApplyStatusConstant.COMPLETED_STR)) {
                throw new ServiceException("该企业已认证请勿重复提交！");
            }
        }
    }

    @Override
    public AjaxResult<CompanyInfo> authentication(CompanyAuthenticationVO companyAuthenticationVO) throws Exception {
        CompanyInfo companyInfo = companyInfoMapper.selectCompanyInfoByCompanyName(companyAuthenticationVO.getCompanyName());
        if(companyInfo==null){
            companyInfo=companyInfoMapper.selectCompanyInfoByUserId(SecurityUtils.getUserId()+"");
        }
        if(companyInfo.getRegisterStatus().equals("true")){
            throw new ServiceException("该企业已认证请勿重复提交！");
        }
        CompanyInfoBindDto companyInfoBindDto = companyInfoMapper.selectCompanyInfoByName(companyInfo.getCompanyName());
        if (companyInfoBindDto != null) {
            // 单位存在的话就需要查询状态
            String applyStatus = companyInfoBindDto.getApplyStatus();
            if(applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW.toString())||applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW_STR)) {
                throw new ServiceException("该单位正处于审批中！");
            }
            if(applyStatus.equals(ApplyStatusConstant.COMPLETED.toString())||applyStatus.equals(ApplyStatusConstant.COMPLETED_STR)) {
                throw new ServiceException("该企业已认证请勿重复提交！");
            }
        }
        BeanUtils.copyProperties(companyAuthenticationVO, companyInfo);
        companyInfoMapper.updateCompanyInfo(companyInfo);
        Long companyId = companyInfo.getCompanyId();
        // 新增完毕之后直接发起流程
        companyApplyService.startFlow(String.valueOf(companyId),String.valueOf(companyInfo.getUserId()));
        return AjaxResult.success(companyInfo);
    }

    @Override
    public CompanyInfo getCompanyOnDesc() {
        SysUser sysUser=userMapper.selectUserById(SecurityUtils.getUserId());
        CompanyInfo companyInfo= companyInfoMapper.selectCompanyInfoByUserId(SecurityUtils.getUserId()+"");
        return companyInfo;
    }

}

